class DataUtils::Geo::SearchMap < DataUtils::DBObject
    @table_name = :location_search_map
    attr_reader :term, :city_id, :region_id, :country_id
    def initialize(params)
        super(params)
        @term = params[:term]
        @city_id= params[:city_id]
        @region_id = params[:region_id]
        @country_id = params[:country_id]
    end
    def self.add_term(term, location)
    	location_key = "#{location.class.class_name.downcase}_id".to_sym
    	params = {:term => term, location_key => location.id}
    	self.find_or_create(params)
    end
    def self.search(term)
    	result = DataUtils::Geo::SearchMap.find_first(:term => term)
    	return nil if(result.nil?)
    	return build_search_result(result)
    end
    private 
    def self.build_search_result(result)
    	params = {}
    	if(result.country_id)
    		params[:country] = DataUtils::Geo::Country.find_first(:id => result.country_id).name
    		params[:confidence] = :country
    	elsif(result.region_id)
    		region = DataUtils::Geo::Region.find_first(:id => result.region_id)
    		params[:region] = region.name
    		params[:country] = region.country.name
    		params[:confidence] = :region
    	elsif(result.city_id)
    		city = DataUtils::Geo::City.find_first(:id => result.city_id)
    		params[:city] = city.name
    		params[:region] = city.region.name unless city.region.nil?
    		params[:country] = city.country.name
    		params[:confidence] = :city
    	end
    	return DataUtils::Geo::SearchResult.new(params)
    end
end
